﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace PropertyManagement.Client.WinFormClient.Forms.Utilies
{
    public class FileUtil
    {
        /// <summary>
        ///从文件还原对象的内容
        /// </summary>
        /// <param name="path">文件名</param>
        /// <returns>被还原的对象</returns>
        public static T LoadFromBinaryFile<T>(string path) where T : new()
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryFormatter f = new BinaryFormatter();
            //还原序列化
            object obj = f.Deserialize(fs);
            fs.Close();

            return (T)obj;
        }

        /// <summary>
        ///对象的内容保存为文件
        /// </summary>
        /// <param name="obj">保存的对象</param>
        /// <param name="path">保存的文件名</param>
        public static void SaveToBinaryFile(object obj, string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();
            //序列化
            bf.Serialize(fs, obj);
            fs.Close();
        }
    }
}
